package y24.m3;

import java.util.Stack;

public class Test15 {
    static class Solution {
        public static String addBinary(String a, String b) {
            StringBuffer num = new StringBuffer("");
            int l = Math.max(a.length(),b.length()) - 1;
            if (a.length() > b.length()){
                b = addZero(a,b);
            }else if (a.length() < b.length()){
                a = addZero(b,a);
            }
            Stack<Character> ch = new Stack<>();
            char i = '0';
            while (l >= 0){
                char ca = a.charAt(l);
                char cb = b.charAt(l);
                if (ca == '1' && cb == '1' || ca == '1' && i == '1' || cb == '1' && i == '1' ){
                    ch.push('0');
                    i = '1';
                } else if (ca == '1' && cb == '0' || ca == '0' && cb == '1' ||ca == '0' && i == '1' || cb == '0' && i == '1') {
                    ch.push('1');
                    i = '0';
                } else {
                    ch.push('0');
                    i = '0';
                }
                l--;
            }
            if (i == '1'){
                num.append('1');
            }
            for (char c:ch) {
                num.append(c);
            }
            return String.valueOf(num);
        }
        public static String addZero(String a,String b){
            StringBuffer zero = new StringBuffer();
            for (int i = 0; i < a.length() - b.length(); i++) {
                zero.append('0');
            }
            for (int i = 0; i < b.length(); i++) {
                zero.append(b.charAt(i));
            }
            return zero.toString();
        }
    }

    public static void main(String[] args) {
        System.out.println(Solution.addBinary("1010", "1011"));
        System.out.println(Solution.addBinary("111", "1"));
        System.out.println(Solution.addBinary("1111", "1"));
        System.out.println(Solution.addBinary("111", "111111111111"));

    }

}
